#!/bin/bash
function redis_alone() {
    echo -e "$Info ${purple}修改配置文件${nocolor}"
    mkdir -p $redisPath/data/$redisPort >/dev/null 2>&1
    /bin/cp -f $redisPath/conf/redis.conf $redisPath/conf/$redisPort.conf 
    sed -i "s/^port.*/port $redisPort/g" $redisPath/conf/$redisPort.conf  
    sed -i "s#^pidfile.*#pidfile $redisPath/pid/redis_$redisPort.pid#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^logfile.*#logfile \"$redisPath/logs/redis_$redisPort.log\"#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^dir.*#dir $redisPath/data/$redisPort#g" $redisPath/conf/$redisPort.conf 
    echo -e "$Info ${purple}启动redis单节点模式${nocolor}"
    if [[ $system_ver != [456] ]];then
        /bin/mv -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis.service  
        systemctl daemon-reload >/dev/null 2>&1
        systemctl start redis.service 
    else
        mv /etc/init.d/redis-$redisPort /etc/init.d/redis  
        /etc/init.d/redis        
    fi
}

function redis_sentinel() {
    echo -e "$Info ${purple}修改配置文件${nocolor}"
    redisPort1=`expr $redisPort + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort1=`expr $redisPort1 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1} "`
        done
    fi
    redisPort2=`expr $redisPort1 + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort2=`expr $redisPort2 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2} "`
        done
    fi
    sentinelPort=`expr $redisPort + 20000`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort} "`
        while [[ -n $PortUsed_Pro ]]
        do
          sentinelPort=`expr $sentinelPort + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort} "`
        done
    fi
    sentinelPort1=`expr $redisPort1 + 20000`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort1} "`
        while [[ -n $PortUsed_Pro ]]
        do
          sentinelPort1=`expr $sentinelPort1 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort1} "`
        done
    fi
    sentinelPort2=`expr $redisPort2 + 20000`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort2} "`
        while [[ -n $PortUsed_Pro ]]
        do
          sentinelPort2=`expr $sentinelPort2 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${sentinelPort2} "`
        done
    fi
    mkdir -p $redisPath/data/{$redisPort,$redisPort1,$redisPort2,$sentinelPort,$sentinelPort1,$sentinelPort2} >/dev/null 2>&1
    #redis配置
    /bin/cp -f $redisPath/conf/redis.conf $redisPath/conf/$redisPort.conf 
    sed -i "s/^port.*/port $redisPort/g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^pidfile.*#pidfile $redisPath/pid/redis_$redisPort.pid#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^logfile.*#logfile \"$redisPath/logs/redis_$redisPort.log\"#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^dir.*#dir $redisPath/data/$redisPort#g" $redisPath/conf/$redisPort.conf 
    
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort1.conf 
    sed -i "s/$redisPort/$redisPort1/g" $redisPath/conf/$redisPort1.conf 
    sed -i "/slaveof <masterip>/a slaveof $ipaddr $redisPort" $redisPath/conf/$redisPort1.conf 
    
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort2.conf 
    sed -i "s/$redisPort/$redisPort2/g" $redisPath/conf/$redisPort2.conf 
    sed -i "/slaveof <masterip>/a slaveof $ipaddr $redisPort" $redisPath/conf/$redisPort2.conf 

    #哨兵配置
    sed -i "s/^sentinel monitor mymaster.*/sentinel monitor mymaster $ipaddr 6379 2/g" $redisPath/conf/sentinel.conf 
    sed -i "/ protected-mode /a protected-mode no" $redisPath/conf/sentinel.conf 
    sed -i "2a daemonize yes" $redisPath/conf/sentinel.conf 
    /bin/cp -f $redisPath/conf/sentinel.conf $redisPath/conf/$sentinelPort.conf 
    
    sed -i "s/^port.*/port $sentinelPort/g" $redisPath/conf/$sentinelPort.conf 
    sed -i "s#^dir.*#dir $redisPath/data/$sentinelPort#g" $redisPath/conf/$sentinelPort.conf 
    sed -i "/^dir/a logfile \"$redisPath/logs/sentinel_$sentinelPort.log\"" $redisPath/conf/$sentinelPort.conf 
    sed -i "/^port/a pidfile \"$redisPath/pid/sentinel_$sentinelPort.pid\"" $redisPath/conf/$sentinelPort.conf 
    
    /bin/cp -f $redisPath/conf/$sentinelPort.conf $redisPath/conf/$sentinelPort1.conf 
    sed -i "s/$sentinelPort/$sentinelPort1/g" $redisPath/conf/$sentinelPort1.conf 
    /bin/cp -f $redisPath/conf/$sentinelPort.conf $redisPath/conf/$sentinelPort2.conf 
    sed -i "s/$sentinelPort/$sentinelPort2/g" $redisPath/conf/$sentinelPort2.conf 
    
    #配置密码
    if [ -n "$redisPasswd" ];then
        sed -i "/ masterauth /a masterauth $redisPasswd" $redisPath/conf/$redisPort1.conf 
        sed -i "/ masterauth /a masterauth $redisPasswd" $redisPath/conf/$redisPort2.conf 
        sed -i "/^sentinel monitor/a sentinel auth-pass mymaster $redisPasswd" $redisPath/conf/$sentinelPort.conf 
        sed -i "/^sentinel monitor/a sentinel auth-pass mymaster $redisPasswd" $redisPath/conf/$sentinelPort1.conf 
        sed -i "/^sentinel monitor/a sentinel auth-pass mymaster $redisPasswd" $redisPath/conf/$sentinelPort2.conf 
    fi
    
    #设置redis服务脚本
    echo -e "$Info ${purple}启动redis哨兵模式${nocolor}"
    if [[ $system_ver != [456] ]];then
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort1.service 
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort2.service 
        sed -i "s/$redisPort/$redisPort1/g" /etc/systemd/system/redis-$redisPort1.service 
        sed -i "s/$redisPort/$redisPort2/g" /etc/systemd/system/redis-$redisPort2.service 
        #哨兵服务脚本
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-sentinel-$sentinelPort.service 
        sed -i "s/redis-server/redis-sentinel/g" /etc/systemd/system/redis-sentinel-$sentinelPort.service 
        sed -i "s/$redisPort/$sentinelPort/g" /etc/systemd/system/redis-sentinel-$sentinelPort.service 
        
        /bin/cp -f /etc/systemd/system/redis-sentinel-$sentinelPort.service /etc/systemd/system/redis-sentinel-$sentinelPort1.service 
        sed -i "s/$sentinelPort/$sentinelPort1/g" /etc/systemd/system/redis-sentinel-$sentinelPort1.service 
        /bin/cp -f /etc/systemd/system/redis-sentinel-$sentinelPort.service /etc/systemd/system/redis-sentinel-$sentinelPort2.service 
        sed -i "s/$sentinelPort/$sentinelPort2/g" /etc/systemd/system/redis-sentinel-$sentinelPort2.service 
        
        systemctl daemon-reload >/dev/null 2>&1
        systemctl start redis-$redisPort.service 
        systemctl start redis-$redisPort1.service    
        systemctl start redis-$redisPort2.service    
        systemctl start redis-sentinel-$sentinelPort    
        systemctl start redis-sentinel-$sentinelPort1 
        systemctl start redis-sentinel-$sentinelPort2 
    else
        # 服务脚本
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort1 
        sed -i "s/^PORT=.*/PORT=$redisPort1/g" /etc/init.d/redis-$redisPort1 
        /bin/cp -f /etc/init.d/redis_$redisPort /etc/init.d/redis-$redisPort2 
        sed -i "s/^PORT=.*/PORT=$redisPort2/g" /etc/init.d/redis-$redisPort2 
        
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-sentinel-$sentinelPort 
        sed -i "s#^EXEC=.*#EXEC=\$REDIS_HOME/bin/redis-sentinel#g" /etc/init.d/redis-sentinel-$sentinelPort 
        sed -i "s/^PORT=.*/PORT=$sentinelPort/g" /etc/init.d/redis-sentinel-$sentinelPort 
        /bin/cp -f /etc/init.d/redis-sentinel_$sentinelPort /etc/init.d/redis-sentinel-$sentinelPort1 
        sed -i "s/^PORT=.*/PORT=$sentinelPort1/g" /etc/init.d/redis-sentinel-$sentinelPort1 
        /bin/cp -f /etc/init.d/redis-sentinel_$sentinelPort /etc/init.d/redis-sentinel_$sentinelPort2 
        sed -i "s/^PORT=.*/PORT=$sentinelPort2/g" /etc/init.d/redis-sentinel-$sentinelPort2 
        # 启动
        /etc/init.d/redis-$redisPort start     
        /etc/init.d/redis-$redisPort1 start     
        /etc/init.d/redis-$redisPort2 start     
        /etc/init.d/redis-sentinel-$sentinelPort start     
        /etc/init.d/redis-sentinel-$sentinelPort1 start     
        /etc/init.d/redis-sentinel-$sentinelPort2 start    
    fi
}

function redis_cluster() {
    echo -e "$Info ${purple}安装Ruby Redis${nocolor}"
    if [ "$die_network" == "false" ];then
        echo -e "$Info ${purple}修改rubygem源${nocolor}"
        gem sources --remove https://rubygems.org/
        gem sources -a https://mirrors.aliyun.com/rubygems/
        gem sources --add https://mirrors.tuna.tsinghua.edu.cn/rubygems/
        echo -e  "$Info ${purple}安装redis.gem${nocolor}" 
        gem install redis -v 3.3.5 
        if [ "$?" != "0" ];then
          echo -e "$Info ${purple}使用本地的redis.gem安装${nocolor}" 
          gem install $redisHome/redis-3.3.5.gem 
        fi
    else
        echo -e "$Info ${purple}使用本地的redis.gem安装${nocolor}" 
        gem install $redisHome/redis-3.3.5.gem 
    fi
    if [ "$?" != "0" ];then
        echo ""
        echo -ne "${Error} ${red}安装redis.gem失败，按任意键退出安装!${nocolor}"
        read -s -n1 goback
        echo -e ""
        return 1
    fi
    echo -e "$Info ${purple}修改配置文件${nocolor}"
    redisPort1=`expr $redisPort + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort1=`expr $redisPort1 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1} "`
        done
    fi
    redisPort2=`expr $redisPort1 + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort2=`expr $redisPort2 + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2} "`
        done
    fi
    redisPort_s=`expr $redisPort2 + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort_s} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort_s=`expr $redisPort_s + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort_s} "`
        done
    fi
    redisPort1_s=`expr $redisPort_s + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1_s} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort1_s=`expr $redisPort1_s + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort1_s} "`
        done
    fi
    redisPort2_s=`expr $redisPort1_s + 1`
    if [ "$PortCheck" == "Yes" ];then
        PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2_s} "`
        while [[ -n $PortUsed_Pro ]]
        do
          redisPort2_s=`expr $redisPort2_s + 1`
          PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort2_s} "`
        done
    fi
    mkdir -p $redisPath/data/{$redisPort,$redisPort1,$redisPort2,$redisPort_s,$redisPort1_s,$redisPort2_s} >/dev/null 2>&1
    
    sed -i "/^# cluster-enabled/a cluster-enabled yes" $redisPath/conf/redis.conf 
    sed -i "/^# cluster-config-file/a cluster-config-file nodes-$redisPort.conf" $redisPath/conf/redis.conf 
    sed -i "/^# cluster-node-timeout/a cluster-node-timeout 15000" $redisPath/conf/redis.conf 
    if [ -n "$redisPasswd" ];then
        sed -i "/ masterauth /a masterauth $redisPasswd" $redisPath/conf/redis.conf 
        sed -i "s/\(@r = Redis\.new(:host.*\))/\1, :password => \"$redisPasswd\")/g" $redisPath/bin/redis-trib.rb 
    fi
    /bin/cp -f $redisPath/conf/redis.conf $redisPath/conf/$redisPort.conf 
    sed -i "s/^port.*/port $redisPort/g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^pidfile.*#pidfile $redisPath/pid/redis_$redisPort.pid#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^logfile.*#logfile \"$redisPath/logs/redis_$redisPort.log\"#g" $redisPath/conf/$redisPort.conf 
    sed -i "s#^dir.*#dir $redisPath/data/$redisPort#g" $redisPath/conf/$redisPort.conf 
    
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort_s.conf 
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort1.conf 
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort1_s.conf 
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort2.conf 
    /bin/cp -f $redisPath/conf/$redisPort.conf $redisPath/conf/$redisPort2_s.conf 
    sed -i "s/$redisPort/$redisPort_s/g" $redisPath/conf/$redisPort_s.conf 
    sed -i "s/$redisPort/$redisPort1/g" $redisPath/conf/$redisPort1.conf 
    sed -i "s/$redisPort/$redisPort1_s/g" $redisPath/conf/$redisPort1_s.conf 
    sed -i "s/$redisPort/$redisPort2/g" $redisPath/conf/$redisPort2.conf 
    sed -i "s/$redisPort/$redisPort2_s/g" $redisPath/conf/$redisPort2_s.conf 
    #服务脚本
    echo -e "$Info ${purple}启动redis集群模式${nocolor}"

    if [ "$system_ver" != "6" ];then
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort_s.service 
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort1.service 
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort1_s.service 
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort2.service 
        /bin/cp -f /etc/systemd/system/redis-$redisPort.service /etc/systemd/system/redis-$redisPort2_s.service 
        sed -i "s/$redisPort/$redisPort_s/g" /etc/systemd/system/redis-$redisPort_s.service 
        sed -i "s/$redisPort/$redisPort1/g" /etc/systemd/system/redis-$redisPort1.service 
        sed -i "s/$redisPort/$redisPort1_s/g" /etc/systemd/system/redis-$redisPort1_s.service 
        sed -i "s/$redisPort/$redisPort2/g" /etc/systemd/system/redis-$redisPort2.service 
        sed -i "s/$redisPort/$redisPort2_s/g" /etc/systemd/system/redis-$redisPort2_s.service 
        systemctl daemon-reload >/dev/null 2>&1
        systemctl start redis-$redisPort.service 
        systemctl start redis-$redisPort_s.service 
        systemctl start redis-$redisPort1.service   
        systemctl start redis-$redisPort1_s.service        
        systemctl start redis-$redisPort2.service  
        systemctl start redis-$redisPort2_s.service 
    else
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort_s 
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort1 
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort1_s 
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort2 
        /bin/cp -f /etc/init.d/redis-$redisPort /etc/init.d/redis-$redisPort2_s 
        sed -i "s/^PORT=.*/PORT=$redisPort_s/g" /etc/init.d/redis-$redisPort_s 
        sed -i "s/^PORT=.*/PORT=$redisPort1/g" /etc/init.d/redis-$redisPort1 
        sed -i "s/^PORT=.*/PORT=$redisPort1_s/g" /etc/init.d/redis-$redisPort1_s 
        sed -i "s/^PORT=.*/PORT=$redisPort2/g" /etc/init.d/redis-$redisPort2 
        sed -i "s/^PORT=.*/PORT=$redisPort2_s/g" /etc/init.d/redis-$redisPort2_s 
        /etc/init.d/redis-$redisPort start   
        /etc/init.d/redis-$redisPort_s start         
        /etc/init.d/redis-$redisPort1 start  
        /etc/init.d/redis-$redisPort1_s start        
        /etc/init.d/redis-$redisPort2 start  
        /etc/init.d/redis-$redisPort2_s start        
    fi
    pidnum=`pidof redis-server|wc|awk '{print $2}'`
    if [ "$pidnum" == "6" ];then
        echo -e "$Info ${purple}创建redis集群${nocolor}"
        echo -e "yes\n"|$redisPath/bin/redis-trib.rb create --replicas 1 $ipaddr:$redisPort $ipaddr:$redisPort1 $ipaddr:$redisPort2 $ipaddr:$redisPort_s $ipaddr:$redisPort1_s $ipaddr:$redisPort2_s 
    else
        echo -e "$Error ${red}redis服务启动异常，无法创建redis集群${nocolor}"
    fi
}

function install_check() {
    redisSuccess=
    if [ "$redis_run_type" == "1" ];then
        redisPid=`pidof redis-server`
        if [ -n "$redisPid" ];then
            if [[ $system_ver == [456] ]];then
                echo -e "$Info ${light_green}Redis安装成功，你可以使用service redis start/stop/status/restart命令管理redis服务${nocolor}"
            else
                echo -e "$Info ${light_green}Redis安装成功，你可以使用systemctl start/stop/status/restart redis命令管理redis服务${nocolor}"
            fi
            redisSuccess=Yes
        else
            echo -e "$Error ${red}Redis安装失败，请检查redis配置文件${nocolor}"
        fi
    elif [ "$redis_run_type" == "2" ];then
        redisPid=`pidof redis-server|wc|awk '{print $2}'`
        sentinelPid=`pidof redis-sentinel|wc|awk '{print $2}'`
        if [ "$redisPid" = "3" -a "$sentinelPid" = "3" ];then
           echo -e "$Info ${light_green}Redis哨兵模式安装成功${nocolor}"
           redisSuccess=Yes
        else
           echo -e "$Error ${red}Redis哨兵模式安装失败${nocolor}"
        fi
    else
        redisPid=`pidof redis-server|wc|awk '{print $2}'`
        if [ "$redisPid" = "6" ];then
            echo -e "$Info ${light_green}Redis集群模式安装成功${nocolor}"
            redisSuccess=Yes
        else
            echo -e "$Error ${red}Redis集群模式安装失败${nocolor}"
        fi
    fi
    if [ "$redisSuccess" == "Yes" ];then
        echo -e "$blue Redis进程信息 $nocolor"
        echo "------------------------------------------------------------------------------"
        ps aux |grep "$redisPath/bin/redis"|grep -v grep|awk '{print $1,$2,$11}'
        echo "------------------------------------------------------------------------------"
    fi
    anykeyback
}


function install_redis() {
echo -e "${blue}当前正在执行的操作为:${nocolor} ${green}安装Redis${nocolor}"
echo ""
redisPid=`pidof redis-server`
sentinelPid=`pidof redis-sentinel`
if [ -n "$redisPid" -o -n "$sentinelPid" ];then
   echo -e  "$Warn 系统中已经有Redis在运行，请先停止或卸载！！！" 
   anykeyback
   return 1
fi

echo -ne "设置redis安装位置[/usr/local/redis]: "
read -e redisPath
redisPath=${redisPath:-/usr/local/redis}
redisPath=`echo $redisPath`
redisPath=${redisPath%/}
echo ""

if [ -d "$redisPath" ];then
   echo -ne "安装目录$redisPath已经存在，继续安装会删除此目录，建议继续安装前做好备份！\n继续[Yy,Enter], 取消[Cc] "
   read isCC
   if [[ $isCC == [Cc] ]];then
      return 1
   fi
   echo ""
fi

redisHome="$workHome/packages/redis"
cd $redisHome
echo -ne "输入需要安装的Redis版本[3.2.13]："
read redisVer
redisVer=${redisVer:-3.2.13}
redisVer=`echo $redisVer`
echo ""

echo -ne "${blue}选择Redis运行模式${nocolor}
1.单机模式
2.哨兵模式
3.集群模式
请选择[1]："
read redis_run_type
if [[ $redis_run_type != [123] ]];then
    redis_run_type=1
fi

if [ "$redis_run_type" == "1" ];then
   runMode="单机模式"
elif [ "$redis_run_type" == "2" ];then
   runMode="哨兵模式"
else
   runMode="集群模式"
fi

if [ "$redis_run_type" == "3" ];then
    main_redisVer=`echo $redisVer|awk -F"." '{print $1}'`
    if [[ $main_redisVer -lt 3 ]];then
        echo -e "$Error Redis集群模式必须使用redis 3以上版本！！！"
        anykeyback
        return 1
    fi
fi
echo ""

command -v ss >/dev/null 2>&1
if [ "$?" == "0" ];then
   listen_cmd="ss -lnpt"
else
   command -v netstat >/dev/null 2>&1
   if [ "$?" == "0" ];then
      listen_cmd="netstat -tnlp"
   fi
fi
[[ $listen_cmd ]] && PortCheck=Yes || PortCheck=No
PortUsed=
PortUsed_Pro=
redisPort=
echo -e "${blue}设置Redis端口${nocolor}
----------------------------------------
若端口为设置为6379，则不同模式端口如下
单机模式
Redis：6379
哨兵模式
Redis：6379-6381 哨兵：26379-26381
集群模式
Redis：6379-6384 节点通讯：Reids端口+1w
----------------------------------------"
while [[ ! "$redisPort" =~ ^[1-9][0-9]+$ || "$PortUsed" == "Yes" ]]
do
    echo -ne "请输入Redis端口[6379]: "
    read redisPort
    redisPort=${redisPort:-6379}
    if [[ ! "$redisPort" =~ ^[1-9][0-9]+$ ]];then
        echo -e "${Warn} redis端口只能为两位及以上的且不以0开头的数字组成，请重新输入！"
        sleep 0.5
    else
        if [ "$PortCheck" == "Yes" ];then
            PortUsed_Pro=`$listen_cmd 2>/dev/null |grep ":${redisPort} "`
            if [ -n "$PortUsed_Pro" ];then
                PortUsed=Yes
                echo -e "${Warn} Redis端口已被使用，请重新输入！"
            else
                PortUsed=No
            fi
        else
            PortUsed=No
        fi
    fi
done
redisPort=`echo $redisPort`
echo ""

echo -ne "输入Redis密码，留空则不使用密码: "
read redisPasswd
redisPasswd=`echo $redisPasswd`
echo ""

echo -ne "${blue}Redis安装信息汇总${nocolor}
---------------------------
Redis版本：$redisVer
Rdis安装位置：$redisPath
Redis端口：$redisPort
Redis运行模式：$runMode
Redis密码：$redisPasswd
---------------------------
继续安装[Yy,Enter]，退出安装[Nn]: "
read isYn
isYn=${isYn:-y}
if [[ $isYn == [Nn] ]];then
   return 1
fi
echo ""

echo -e "${cyan}将开始redis安装过程${nocolor}"
echo ""
if [ "$die_network" == "true" ];then
    ping -c 2 -w 5 180.76.76.76 >/dev/null 2>&1
    if [ "$?" != "0" ];then
        die_network="true"
    else
        die_network="false"
    fi
fi

if [[ ! -f $redisHome/redis-$redisVer.tar.gz && "$die_network" == "false" ]];then
    echo -e "$Info ${purple}下载redis${nocolor}" 
    curl --progress-bar --fail -O http://download.redis.io/releases/redis-$redisVer.tar.gz 
    if [ "$?" != "0" ];then
        rm -rf $redisHome/redis-$redisVer.tar.gz
        echo -e "$Info ${purple}尝试使用wget下载${nocolor}"
        wget -t5 http://download.redis.io/releases/redis-$redisVer.tar.gz 
    fi
           
    if [ "$?" != "0" ];then
        echo -e "$Error 下载Redis失败，请检查网络或者不存在此版本的Redis！！！"
        anykeyback
        return 1
    fi
elif [[ ! -f $redisHome/redis-$redisVer.tar.gz && "$die_network" == "true" ]];then
    echo -e "$Error 你的主机未联网，请提前手动下载安装包，使用离线安装！！！"
    anykeyback
    return 1
fi


echo -e "$Info ${purple}安装所需基础RPM包${nocolor}"
sleep 1

if [ "$redis_run_type" == "3" ];then
    yum -y install gcc glibc gcc-c++ tcl jemalloc ruby rubygems 
else
   yum -y install gcc glibc gcc-c++ tcl jemalloc
fi
if [ "$?" != "0" ];then
    echo -e "$Error 基础依赖软件失败，退出安装！！！"
    anykeyback
    return 1
fi
find $redisHome/* -type d|xargs rm -rf

echo -e "$Info ${purple}解压Redis安装包${nocolor}"
cd $redisHome
tar zxf redis-$redisVer.tar.gz && \
cd redis-$redisVer && \
echo -e "$Info ${purple}编译Redis${nocolor}" && \
sleep 1 && \
make -j8 && \
echo -e "$Info ${purple}安装Redis${nocolor}" && \
sleep 1 && \
make install

if [ "$?" != "0" ];then
    echo -e "$Error 安装Redis失败，退出安装！！！"
    anykeyback
    return 1
fi

echo " "
echo -e "$Info ${purple}复制Redis到安装目录${nocolor}"
rm -rf $redisPath
mkdir -p $redisPath/{bin,conf,logs,pid,data}
cd $redisHome/redis-$redisVer
/bin/cp -f redis.conf sentinel.conf $redisPath/conf/ 
cd src/
/bin/cp -f redis-cli redis-sentinel redis-trib.rb redis-server redis-benchmark redis-check-aof $redisPath/bin 
for i in `ls -F |grep "\*"`
do
   /bin/cp -f $i $redisPath/bin/ >/dev/null 2>&1
done
chmod +x $redisPath/bin/*

echo -e "$Info ${purple}修改Redis通用配置${nocolor}"
sed -i "s/^bind.*/bind $ipaddr/g" $redisPath/conf/redis.conf 
sed -i "s/^daemonize.*/daemonize yes/g" $redisPath/conf/redis.conf 
if [ -n "$redisPasswd" ];then
   sed -i "/[# ]*requirepass .*/a requirepass $redisPasswd" $redisPath/conf/redis.conf  
fi
if [[ $system_ver == [456] ]];then
   cat >/etc/init.d/redis-$redisPort<<'EOF'
#!/bin/bash
#
# redis - this script starts and stops the redis-server daemon
#
# chkconfig:   - 85 15
# description:  Redis is a persistent key-value database
# processname: redis-server
  
# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network
  
# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

PORT=6379
REDIS_HOME=/usr/local/redis
EXEC=$REDIS_HOME/bin/redis-server
PROG=$(basename $EXEC)
if [ "$PROG" == "redis-server" ];then
    PREFIX=redis
else
    PREFIX=sentinel
fi
CONF_FILE=$REDIS_HOME/conf/$PORT.conf
PID_FILE=$REDIS_HOME/pid/$PREFIX_${PORT}.pid
lockfile=/var/lock/subsys/$PREFIX_$PORT


start() {
    [ -x $EXEC ] || exit 5
    [ -f $CONF_FILE ] || exit 6
    echo -n $"Starting $PROG: "
    daemon $EXEC $CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}
  
stop() {
    echo -n $"Stopping $PROG: "
    killproc -p $PID_FILE $PROG
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}
  
restart() {
    stop
    start
}
  
reload() {
    echo -n $"Reloading $PROG: "
    killproc -p $PID_FILE $EXEC -HUP
    RETVAL=$?
    echo
}

  
rh_status() {
    status -p $PID_FILE $PROG
}
  
rh_status_q() {
    rh_status >/dev/null 2>&1
}
  
case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    status)
        rh_status
        ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|reload}"
        exit 2
esac
EOF
    sed -i "s/^REDIS_HOME=.*/REDIS_HOME=$redisPath/g" /etc/init.d/redis-$redisPort 
    sed -i "s/^PORT=.*/PORT=$redisPort/g" /etc/init.d/redis-$redisPort 
    chmod +x /etc/init.d/redis-$redisPort
else
    cat >/etc/systemd/system/redis-$redisPort.service<<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target
After=network-online.target
Wants=network-online.target

[Service]
ExecStart=$redisPath/bin/redis-server $redisPath/conf/$redisPort.conf --supervised systemd
ExecStop=/usr/libexec/redis-shutdown redis-server $redisPath/conf/$redisPort.conf
Type=notify

[Install]
WantedBy=multi-user.target
EOF
        cat>/usr/libexec/redis-shutdown<<'EOF'
#!/bin/bash
#
# Wrapper to close properly redis and sentinel
test x"$REDIS_DEBUG" != x && set -x

REDIS_CLI=/usr/bin/redis-cli

# Retrieve service name
SERVICE_NAME="$1"
if [ -z "$SERVICE_NAME" ]; then
   SERVICE_NAME=redis-server
fi

# Get the proper config file based on service name
CONFIG_FILE="$2"

# Use awk to retrieve host, port from config file
HOST=`awk '/^[[:blank:]]*bind/ { print $2 }' $CONFIG_FILE | tail -n1`
PORT=`awk '/^[[:blank:]]*port/ { print $2 }' $CONFIG_FILE | tail -n1`
PASS=`awk '/^[[:blank:]]*requirepass/ { print $2 }' $CONFIG_FILE | tail -n1`
SOCK=`awk '/^[[:blank:]]*unixsocket\s/ { print $2 }' $CONFIG_FILE | tail -n1`

# Just in case, use default host, port
HOST=${HOST:-127.0.0.1}
if [ "$SERVICE_NAME" = redis-server ]; then
    PORT=${PORT:-6379}
else
    PORT=${PORT:-26739}
fi

# Setup additional parameters
# e.g password-protected redis instances
[ -z "$PASS"  ] || ADDITIONAL_PARAMS="-a $PASS"

# shutdown the service properly
if [ -e "$SOCK" ] ; then
    $REDIS_CLI -s $SOCK $ADDITIONAL_PARAMS shutdown
else
    $REDIS_CLI -h $HOST -p $PORT $ADDITIONAL_PARAMS shutdown
fi
EOF
    sed -i "s#^REDIS_CLI=.*#REDIS_CLI=$redisPath/bin/redis-cli#g" /usr/libexec/redis-shutdown 
fi
    
if [ "$redis_run_type" == "1" ];then
    redis_alone
elif [ "$redis_run_type" == "2" ];then
    redis_sentinel
else
    redis_cluster     
fi
        
install_check
}




